/*
 * ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <rom.prevot@gmail.com> wrote this file. As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return R. Prevot
 * ----------------------------------------------------------------------------
 */

/******************************************************************************\
 *          ____                _______    _____ _             _              *
 *         |  _ \              |__   __|  / ____| |           | |             *
 *         | |_) | ___  _ __ _ __ | | ___| (___ | |_ ___   ___| | __          *
 *         |  _ < / _ \| '__| '_ \| |/ _ \\___ \| __/ _ \ / __| |/ /          *
 *         | |_) | (_) | |  | | | | | (_) |___) | || (_) | (__|   <           *
 *         |____/ \___/|_|  |_| |_|_|\___/_____/ \__\___/ \___|_|\_\          *
 *                                                                            *
\******************************************************************************/

package app.views;

import app.App;
import app.events.ReferenceListener;
import app.events.eventobjects.ReferenceAddedEvent;
import app.events.eventobjects.ReferenceDeletedEvent;
import app.events.eventobjects.ReferenceUpdatedEvent;
import app.models.Categorie;
import app.models.Photo;
import app.models.Reference;
import java.awt.Image;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import org.jdesktop.swingx.JXImagePanel.Style;
import tests.ThumbNailFileView;

/**
 *
 * @author PREVROMA
 */
public class AddReferencePan extends javax.swing.JPanel implements ReferenceListener {

    Map<String, Categorie> categories;

    /** Creates new form AddReferencePan */
    public AddReferencePan() {
        initComponents();
        categories = new HashMap<String, Categorie>();
        prepareGui();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        fileChooser = new javax.swing.JFileChooser();
        jPanel2 = new javax.swing.JPanel();
        btVider = new javax.swing.JButton();
        btOk = new javax.swing.JButton();
        imagePan = new org.jdesktop.swingx.JXImagePanel();
        jPanel3 = new javax.swing.JPanel();
        txtVendu = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtDesignation = new javax.swing.JTextField();
        btPix = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        txtStock = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtFileName = new javax.swing.JTextField();
        txtPxVente = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        cbCategories = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        txtPxAchat = new javax.swing.JTextField();

        FormListener formListener = new FormListener();

        fileChooser.setDialogTitle("Selectionner une photo");
        fileChooser.setForeground(java.awt.Color.white);

        btVider.setText("Vider");
        btVider.setBorderPainted(false);
        btVider.setContentAreaFilled(false);
        btVider.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btVider.addActionListener(formListener);

        btOk.setIcon(App.createIcon("resources/accept.png"));
        btOk.setText("Ajouter");
        btOk.addActionListener(formListener);

        imagePan.setBackground(new java.awt.Color(204, 204, 204));
        imagePan.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout imagePanLayout = new javax.swing.GroupLayout(imagePan);
        imagePan.setLayout(imagePanLayout);
        imagePanLayout.setHorizontalGroup(
            imagePanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 190, Short.MAX_VALUE)
        );
        imagePanLayout.setVerticalGroup(
            imagePanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 209, Short.MAX_VALUE)
        );

        txtVendu.setMinimumSize(new java.awt.Dimension(60, 20));
        txtVendu.setPreferredSize(new java.awt.Dimension(60, 20));

        jLabel4.setText("Qte en stock : ");

        btPix.setText("Choisir...");
        btPix.addActionListener(formListener);

        jLabel9.setText("Photo :");

        jLabel8.setText("(TTC)");

        txtStock.setMinimumSize(new java.awt.Dimension(60, 20));
        txtStock.setPreferredSize(new java.awt.Dimension(60, 20));

        jLabel5.setText("Qte vendue : ");

        jLabel3.setText("Prix de vente : ");

        jLabel1.setText("Désignation : ");

        jLabel6.setText("Catégorie :");

        txtFileName.setEditable(false);
        txtFileName.setText("Aucune");

        txtPxVente.setMinimumSize(new java.awt.Dimension(60, 20));
        txtPxVente.setPreferredSize(new java.awt.Dimension(60, 20));

        jLabel7.setText("(HT)");

        cbCategories.setEditable(true);

        jLabel2.setText("Prix d'achat :");

        txtPxAchat.setMinimumSize(new java.awt.Dimension(60, 20));
        txtPxAchat.setPreferredSize(new java.awt.Dimension(60, 20));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel9)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(cbCategories, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtStock, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(txtPxAchat, javax.swing.GroupLayout.DEFAULT_SIZE, 63, Short.MAX_VALUE)
                                    .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel5))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtPxVente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(txtVendu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(txtDesignation, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jLabel8))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addComponent(txtFileName)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btPix)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtDesignation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(txtPxAchat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtPxVente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtVendu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(cbCategories, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtFileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btPix)
                    .addComponent(jLabel9))
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(imagePan, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(btVider)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btOk)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(imagePan, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btOk)
                            .addComponent(btVider))))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == btVider) {
                AddReferencePan.this.btViderActionPerformed(evt);
            }
            else if (evt.getSource() == btOk) {
                AddReferencePan.this.btOkActionPerformed(evt);
            }
            else if (evt.getSource() == btPix) {
                AddReferencePan.this.btPixActionPerformed(evt);
            }
        }
    }// </editor-fold>//GEN-END:initComponents

    private void btPixActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPixActionPerformed
        fileChooser.setFileFilter(new ImageFileFilter());
        fileChooser.setAccessory(new ThumbNailFileView(fileChooser));
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        
        if (JFileChooser.APPROVE_OPTION == fileChooser.showOpenDialog(this)) {
            File f = fileChooser.getSelectedFile();
            String oldFilename = txtFileName.getText();
            txtFileName.setText("Chargement...");
            String fileName = App.saveFile(f);
            if(!"".equals(fileName)){
                Image img = App.createPhoto(fileName);//.getScaledInstance(imagePan.getWidth(), imagePan.getHeight(), Image.SCALE_REPLICATE);
                imagePan.setStyle(Style.SCALED_KEEP_ASPECT_RATIO);
                imagePan.setImage(img);
                txtFileName.setText(fileName);
            } else {
                App.displayMessage("Impossible de charger la photo", 
                        App.MESSAGE_TYPE.ERROR);
                txtFileName.setText(oldFilename);
            }
            
        }
    }//GEN-LAST:event_btPixActionPerformed

    private void btOkActionPerformed(java.awt.event.ActionEvent evt) {

        String designation = txtDesignation.getText();
        String strCat = (String) cbCategories.getSelectedItem();
        Double pxAchat = null,
                pxVente = null;
        Integer nbStock = null,
                nbVendu = null;
        //@todo Verifier les valeurs           
        try {
            pxAchat = Double.parseDouble(txtPxAchat.getText());
        } catch (NumberFormatException nfe) {
            App.displayMessage("Faudrait saisir le prix d'achat svp!", 
                    App.MESSAGE_TYPE.ERROR);
            return;
        }
        try {
            pxVente = Double.parseDouble(txtPxVente.getText());
        } catch (NumberFormatException nfe) {
            App.displayMessage("Faudrait saisir le prix de vente svp!", 
                    App.MESSAGE_TYPE.ERROR);
            return;
        }
        try {
            nbStock = Integer.parseInt(txtStock.getText());
        } catch (NumberFormatException nfe) {
            App.displayMessage("Faudrait saisir le nombre en stock svp!", 
                    App.MESSAGE_TYPE.ERROR);
            return;
        }
        try {
            nbVendu = Integer.parseInt(txtVendu.getText());
        } catch (NumberFormatException nfe) {
            App.displayMessage("Faudrait saisir le bomvre vendu svp!", 
                    App.MESSAGE_TYPE.ERROR);
            return;
        }
        Categorie cat;
        if (categories.containsKey(strCat)) {
            cat = categories.get(strCat);
        } else {
            cat = new Categorie(strCat);
        }
        Reference ref = new Reference();
        ref.setCategorie(cat);
        ref.setDesignation(designation);
        ref.setPxAchatHT(pxAchat);
        ref.setPxVenteTTC(pxVente);
        ref.setStock(nbStock);
        ref.setVendu(nbVendu);
        ref.setDisponible(true);
        Photo p = new Photo("");
        if(!"aucune".equals(txtFileName.getText())){
            p.setFileName(txtFileName.getText());
        }
        ref.setPhoto(p);
        ajouterReference(ref);
    }

    private void btViderActionPerformed(java.awt.event.ActionEvent evt) {
        prepareGui();
    }

    public void ajouterReference(Reference ref) {
        App.getInstance().getCatalogue().addReference(ref);
        App.displayMessage(ref.getDesignation() + " a été ajoutée", App.MESSAGE_TYPE.INFO);
        prepareGui();
    }

    public void prepareGui() {
        txtDesignation.setText("");
        txtPxAchat.setText("0.00");
        txtPxVente.setText("0.00");
        txtStock.setText("");
        txtVendu.setText("");
        imagePan.setImage(null);
        txtFileName.setText("Aucune");
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btOk;
    private javax.swing.JButton btPix;
    private javax.swing.JButton btVider;
    private javax.swing.JComboBox cbCategories;
    private javax.swing.JFileChooser fileChooser;
    private org.jdesktop.swingx.JXImagePanel imagePan;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTextField txtDesignation;
    private javax.swing.JTextField txtFileName;
    private javax.swing.JTextField txtPxAchat;
    private javax.swing.JTextField txtPxVente;
    private javax.swing.JTextField txtStock;
    private javax.swing.JTextField txtVendu;
    // End of variables declaration//GEN-END:variables

    @Override
    public void onReferenceAdded(ReferenceAddedEvent rae) {
        Categorie cat = rae.getReference().getCategorie();
        //if we haven't register this category yet
        if (!categories.containsKey(cat.getLibelle())) {
            categories.put(cat.getLibelle(), cat);
            cbCategories.addItem(cat.getLibelle());
        }
    }

    @Override
    public void onReferenceDeleted(ReferenceDeletedEvent rde) {
        //Still do nothing!
    }

    @Override
    public void onReferenceUpdated(ReferenceUpdatedEvent rue) {
        //wait for it...
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * Filefilter to filter only image and folders
     */
    static public class ImageFileFilter extends FileFilter {

        private final String[] okFileExtensions =
                new String[]{"jpg", "png", "gif"};

        @Override
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }
            for (String extension : okFileExtensions) {
                if (f.getName().toLowerCase().endsWith(extension)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public String getDescription() {
            return "Photo jpg, png, gif et c'est tout!";
        }
    }
}
